package org.summerframework.component.security.spring.exception;

import org.summerframework.core.util.HandlerMethodUtil;
import org.summerframework.core.util.ViewUtil;
import org.summerframework.web.exception.FilterFailureHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.servlet.HandlerExecutionChain;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石超
 * @version v1.0.0
 */
public class UrlAuthenticationFailureHandler extends FilterFailureHandler implements AuthenticationEntryPoint, AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        failure(request, response, exception);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        failure(request, response, authException);
    }

    @Override
    public void failure(HttpServletRequest request, HttpServletResponse response, Exception authException) {
        HandlerExecutionChain handlerExecutionChain = HandlerMethodUtil.getHandlerMethod(requestMappingHandlerMapping, request);

        if (handlerExecutionChain != null) {
            ViewUtil.render(uriExposeExceptionResolver.resolveException(request, response, handlerExecutionChain.getHandler(), authException), request, response);
        } else {
            ViewUtil.render(uriExposeExceptionResolver.resolveException(request, response, null, authException), request, response);
        }
    }
}
